package br.cin.ufpe.in1118.middleware.distribution;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;

import br.cin.ufpe.in1118.middleware.communication.Transport;
import br.cin.ufpe.in1118.middleware.distribution.handlers.ClientRequestHandler;
import br.cin.ufpe.in1118.middleware.distribution.message.Message;
import br.cin.ufpe.in1118.middleware.exceptions.RemoteException;

public class Requestor {

	private ClientRequestHandler clientHandler;
	private Random random = new Random();

	public Requestor(Transport transport) {
		this.clientHandler = new ClientRequestHandler(transport);
	}

	public Object invoke(Object objectId, String operation,
			Object... parameters) throws RemoteException {
		try {
			Object ret = null;

			Message message = new Message(objectId, operation,
					new ArrayList<Object>(Arrays.asList(parameters)), null);

			long messageId = random.nextLong();
			
			message.setMessageId(messageId);
			
			this.clientHandler.send(message);
			Message msg = this.clientHandler.receive();
			ret = msg.getReturn();
			
			if (msg.hasException()) {
				throw (Exception) ret;
			}
			
			return ret;
		} catch (Exception e) {
			throw new RemoteException(e);
		} finally {
			this.clientHandler.close();
		}
	}

}
